package Server;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.lang.Thread;

public class ChatterServer 
{
	private ServerSocket chatter;
	private int port = 1234;
	public boolean running = true;
	public ArrayList<ConnectionHandler> clients = new ArrayList<ConnectionHandler>();
	private ArrayList<User> database = new ArrayList<User>();
	User u1 = new User("user1", "pass1");
	User u2 = new User("user2", "pass2");
	User u3 = new User("user3", "pass3");
	User u4 = new User("user4", "pass4");
	
	public ChatterServer()
	{
		try {
			chatter = new ServerSocket(port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		database.add(u1);
		database.add(u2);
		database.add(u3);
		database.add(u4);
	}
	
	public static void main(String[] args) 
	{
		ChatterServer cs = new ChatterServer();
		cs.Run();
	}

	private void Run() 
	{
		while(running)
		{
			Socket socket;
			try {
				socket = chatter.accept();
				ConnectionHandler ch = new ConnectionHandler(socket, this);
				Thread client = new Thread(ch);
				client.start();
				clients.add(ch);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	public void Dispatch(String message)
	{
		for (ConnectionHandler cg : clients)
		{
			ObjectOutputStream oos;
			try {
				oos = new ObjectOutputStream(cg.socket.getOutputStream());
				oos.writeObject(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
